package com.probiz.estore.content.dao.impl;


import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.probiz.estore.common.model.content.AdPositionType;
import com.probiz.estore.common.model.content.Advertisement;
import com.probiz.estore.content.dao.AdPositionTypeDao;
import com.probiz.estore.content.dao.AdvertisementDao;
import com.probiz.estore.core.dao.impl.HibernateGenericDaoImpl;


/**
 * Advertisement Data Access Object (DAO) implementation.
 * Developer introduced interfaces should be declared here. Won't get overwritten.
*/
public class AdvertisementDaoImpl  extends HibernateGenericDaoImpl<Advertisement> implements AdvertisementDao {
	private AdPositionTypeDao adPositionTypeDao;
	
	public void setAdPositionTypeDao(AdPositionTypeDao adPositionTypeDao) {
		this.adPositionTypeDao = adPositionTypeDao;
	}

	public List<Advertisement>  getAdvertisementsForFront(final Integer adPositionTypeId ,final Integer categoryId,final  String categoryIds){
		final AdPositionType adPositionType = adPositionTypeDao.getById(adPositionTypeId);
		if(adPositionType == null){
			return new ArrayList<Advertisement>();
		}
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)	throws HibernateException, SQLException {
				StringBuffer hql = new StringBuffer(300);
				hql.append("from Advertisement ad where ad.status = ").append(Advertisement.STATUS_PUBLISHED);
				hql.append(" and ad.adPositionType.adPositionTypeId = ").append(adPositionTypeId);
				if(AdPositionType.POSITION_TYPE_PRODUCTCATEGORY.equals(adPositionType.getPositionType())){
					hql.append(" and ad.advertisementId in (");
					hql.append("      select pa.advertisement.advertisementId from ProductAdvertisement pa where (pa.isSubIncluded <> 1 and pa.categoryId = ").append(categoryId).append(")");
					hql.append("      or (pa.isSubIncluded = 1 and pa.categoryId in (").append(categoryIds).append(") )");
					hql.append(" )");
				}
				hql.append(" order by ad.sortOrder asc");
				Query query = session.createQuery(hql.toString());
				List<Advertisement> rows = (List<Advertisement>) query.list();
				return rows;
			}

		});
		return list;
	}


	
}